package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.service.IFriendsLifeCyclePhaseService;
import com.ibeeking.found.cop.b.rest.service.IFriendsLifeCycleService;
import com.ibeeking.found.cop.service.common.dos.*;
import com.ibeeking.found.cop.service.common.param.FriendsLifeCycleParam;

import com.ibeeking.found.cop.service.common.param.FriendsLifeCyclePhaseParam;
import com.ibeeking.found.cop.service.common.param.FriendsLifeCycleRightParam;
import com.ibeeking.found.cop.service.common.query.FriendsLifeCycleQuery;
import com.ibeeking.found.cop.service.common.vo.FriendsLifeCyclePhaseVO;
import com.ibeeking.found.cop.service.common.vo.FriendsLifeCycleRightVO;
import com.ibeeking.found.cop.service.common.vo.FriendsLifeCycleVO;
import com.ibeeking.found.cop.service.mapper.*;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName FriendsLifeCycleServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class FriendsLifeCycleServiceImpl extends ServiceImpl<FriendsLifeCycleMapper, FriendsLifeCycleDO> implements IFriendsLifeCycleService {

    private static String SHORT_TIME_FORMATTER = "HH:mm:ss";

    @Resource
    private FriendsLifeCycleMapper friendsLifeCycleMapper;

    @Resource
    private FriendsLifeCyclePhaseMapper friendsLifeCyclePhaseMapper;

    @Resource
    private IFriendsLifeCyclePhaseService friendsLifeCyclePhaseServiceImpl;

    @Resource
    private FriendsLifeCycleRightMapper friendsLifeCycleRightMapper;

    @Resource
    private CopDepartmentMapper copDepartmentMapper;

    @Resource
    private CopEmployeeMapper copEmployeeMapper;

    @Override
    public List<FriendsLifeCycleVO> list(FriendsLifeCycleQuery query) {
        List<FriendsLifeCycleDO> entityDOS = friendsLifeCycleMapper.selectList(new LambdaQueryWrapper<FriendsLifeCycleDO>()
                .eq(query.getId() != null, FriendsLifeCycleDO::getId, query.getId())
                .like(StringUtils.isNotBlank(query.getName()), FriendsLifeCycleDO::getName, query.getName())
                .eq(query.getStatus() != null, FriendsLifeCycleDO::getStatus, query.getStatus())
                .orderByDesc(FriendsLifeCycleDO::getCreateTime)
        );
        List<FriendsLifeCycleVO> entityVOS =JsonUtils.jsonToList(entityDOS, FriendsLifeCycleVO.class);
        if(Collections3.isNotEmpty(entityVOS)) {
            List<CopDepartmentDO> copDepartmentDOS = copDepartmentMapper.selectList(new LambdaQueryWrapper<CopDepartmentDO>());
            Map<Long, String> copDepartmentNameCnMaps = Collections3.isNotEmpty(copDepartmentDOS)?copDepartmentDOS.parallelStream().collect(Collectors.toMap(CopDepartmentDO::getId, CopDepartmentDO::getName, (o, n) -> o)):null;

            List<CopEmployeeDO> copEmployeeDOS = copEmployeeMapper.selectList(new LambdaQueryWrapper<CopEmployeeDO>());
            Map<Long, String> copEmployeeNameMaps = Collections3.isNotEmpty(copEmployeeDOS)?copEmployeeDOS.stream().collect(Collectors.toMap(CopEmployeeDO::getId, CopEmployeeDO::getEmployeeName, (o, n) -> n)):null;
            LogUtils.info("=========copEmployeeNameMaps:{}=============",JsonUtils.toJsonStr(copEmployeeNameMaps));
            List<Long> lifeCycleIdList = entityVOS.stream().map(FriendsLifeCycleVO::getId).collect(Collectors.toList());
            List<FriendsLifeCyclePhaseDO> friendsLifeCyclePhaseDOS = friendsLifeCyclePhaseMapper.selectList(new LambdaQueryWrapper<FriendsLifeCyclePhaseDO>().in(FriendsLifeCyclePhaseDO::getCycleId, lifeCycleIdList).orderByAsc(FriendsLifeCyclePhaseDO::getSort));
            Map<Long, List<FriendsLifeCyclePhaseDO>> friendsLifeCyclePhaseDOMap = Collections3.isNotEmpty(friendsLifeCyclePhaseDOS)?friendsLifeCyclePhaseDOS.stream().collect(Collectors.groupingBy(FriendsLifeCyclePhaseDO::getCycleId)):null;
            List<FriendsLifeCycleRightDO> friendsLifeCycleRightDOS = friendsLifeCycleRightMapper.selectList(new LambdaQueryWrapper<FriendsLifeCycleRightDO>().in(FriendsLifeCycleRightDO::getCycleId, lifeCycleIdList));
            Map<Long, List<FriendsLifeCycleRightDO>> friendsLifeCycleRightDOMap = Collections3.isNotEmpty(friendsLifeCycleRightDOS)?friendsLifeCycleRightDOS.stream().collect(Collectors.groupingBy(FriendsLifeCycleRightDO::getCycleId)):null;
            entityVOS.forEach(x -> {
                List<FriendsLifeCyclePhaseDO> friendsLifeCyclePhaseDOList = friendsLifeCyclePhaseDOMap!=null?friendsLifeCyclePhaseDOMap.get(x.getId()):null;
                if(Collections3.isNotEmpty(friendsLifeCyclePhaseDOList)){
                    List<FriendsLifeCyclePhaseVO> friendsLifeCyclePhaseVOList = JsonUtils.jsonToList(friendsLifeCyclePhaseDOList, FriendsLifeCyclePhaseVO.class);
                    friendsLifeCyclePhaseVOList.stream().forEach(d->{
                        String needNotifyStr = "员工跟进提醒：客户未跟进时间超过" + d.getDaysMissing() + "天后，于" + d.getTimeNotify() + "提醒员工跟进";
                        d.setNeedNotifyStr(needNotifyStr);
                        String needCycleNotifyStr = "周期提醒：员工首次提醒未跟进，每" + d.getDaysCycleNotify() + "天，于" + d.getTimeNotifyCycle() + "再次提醒";
                        d.setNeedCycleNotifyStr(needCycleNotifyStr);
                    });
                    List<String> lifeCyclePhaseNameList = friendsLifeCyclePhaseVOList.stream().map(FriendsLifeCyclePhaseVO::getName).collect(Collectors.toList());

                    x.setLifeCyclePhaseStr(StringUtils.join(lifeCyclePhaseNameList.toArray(),"->"));
                    x.setLifeCyclePhases(friendsLifeCyclePhaseVOList);
                }
                List<FriendsLifeCycleRightDO> friendsLifeCycleRightDOList = friendsLifeCycleRightDOMap!=null?friendsLifeCycleRightDOMap.get(x.getId()):null;
                if(Collections3.isNotEmpty(friendsLifeCycleRightDOList)){
                    List<String> lifeCycleRightNameList = new ArrayList<>();
                    List<FriendsLifeCycleRightVO> friendsLifeCycleRightVOList = friendsLifeCycleRightDOList.stream().map(d->{
                        FriendsLifeCycleRightVO friendsLifeCycleRightVO = BeanUtil.convertBean(d, FriendsLifeCycleRightVO.class);
                        if(d.getEmployeeId()!=null){
                            String employeeName = copEmployeeNameMaps!=null?copEmployeeNameMaps.get(d.getEmployeeId()):"";
                            lifeCycleRightNameList.add(employeeName);
                            friendsLifeCycleRightVO.setEmployeeName(employeeName);
                            friendsLifeCycleRightVO.setName(employeeName);
                        }else{
                            String departmentName = copDepartmentNameCnMaps!=null?copDepartmentNameCnMaps.get(d.getDepartmentId()):"";
                            lifeCycleRightNameList.add(departmentName);
                            friendsLifeCycleRightVO.setDepartmentName(departmentName);
                            friendsLifeCycleRightVO.setName(departmentName);
                        }
                        return friendsLifeCycleRightVO;
                    }).collect(Collectors.toList());
                    if(Collections3.isNotEmpty(lifeCycleRightNameList)){
                        x.setLifeCycleRightStr(StringUtils.join(lifeCycleRightNameList.toArray(),";"));
                    }
                    x.setLifeCycleRights(friendsLifeCycleRightVOList);
                }
                x.setStatusDesc(PublishStatusEnum.getName(x.getStatus()));
            });
        }
        LogUtils.info("=========List FriendsLifeCycleVO:{}=============",JsonUtils.toJsonStr(entityVOS));
        return entityVOS;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(FriendsLifeCycleParam param) {
        checkUnique(param);
        FriendsLifeCycleDO entityDO = BeanUtil.convertBean(param, FriendsLifeCycleDO.class);
        Long cycleId = GenerateId.generateId();
        entityDO.setId(cycleId);
        entityDO.setStatus(PublishStatusEnum.DISABLE.getValue());
        entityDO.setCreateBy(UserUtils.getUserId());
        entityDO.setCreateTime(LocalDateTime.now());
        entityDO.setModifyTime(LocalDateTime.now());
        List<FriendsLifeCyclePhaseParam> lifeCyclePhaseParamList = param.getLifeCyclePhases();
        List<FriendsLifeCycleRightParam> lifeCycleRightParamList = param.getLifeCycleRights();
        if(Collections3.isNotEmpty(lifeCyclePhaseParamList)){
            List<FriendsLifeCyclePhaseDO> lifeCyclePhaseDOList = lifeCyclePhaseParamList.stream().map(d->{
                FriendsLifeCyclePhaseDO friendsLifeCyclePhaseDO = BeanUtil.convertBean(d, FriendsLifeCyclePhaseDO.class);
                friendsLifeCyclePhaseDO.setCycleId(cycleId);

                friendsLifeCyclePhaseDO.setCreateBy(UserUtils.getUserId());
                friendsLifeCyclePhaseDO.setCreateTime(LocalDateTime.now());
                friendsLifeCyclePhaseDO.setModifyTime(LocalDateTime.now());
                return friendsLifeCyclePhaseDO;
            }).collect(Collectors.toList());
            friendsLifeCyclePhaseMapper.insertBatchSomeColumn(lifeCyclePhaseDOList);
        }
        if(Collections3.isNotEmpty(lifeCycleRightParamList)){
            List<FriendsLifeCycleRightDO> lifeCycleRightDOList = lifeCycleRightParamList.stream().map(d->{
                FriendsLifeCycleRightDO friendsLifeCycleRightDO = BeanUtil.convertBean(d, FriendsLifeCycleRightDO.class);
                friendsLifeCycleRightDO.setCycleId(cycleId);
                friendsLifeCycleRightDO.setCreateBy(UserUtils.getUserId());
                friendsLifeCycleRightDO.setCreateTime(LocalDateTime.now());
                friendsLifeCycleRightDO.setModifyTime(LocalDateTime.now());
                return friendsLifeCycleRightDO;
            }).collect(Collectors.toList());
            friendsLifeCycleRightMapper.insertBatchSomeColumn(lifeCycleRightDOList);
        }
        return friendsLifeCycleMapper.insert(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(FriendsLifeCycleParam param) {
        FriendsLifeCycleDO entityDO = BeanUtil.convertBean(param, FriendsLifeCycleDO.class);
        Long cycleId = param.getId();
        if(cycleId == null) throw new BusinessException("从前端获取参数出错！");
        entityDO.setStatus(PublishStatusEnum.DISABLE.getValue());
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        List<FriendsLifeCyclePhaseParam> lifeCyclePhaseParamList = param.getLifeCyclePhases();
        List<FriendsLifeCycleRightParam> lifeCycleRightParamList = param.getLifeCycleRights();
        if(Collections3.isNotEmpty(lifeCyclePhaseParamList)){
            List<FriendsLifeCyclePhaseParam> needInsertFriendsLifeCyclePhaseParamList = lifeCyclePhaseParamList.stream().filter(d->(d.getId() == null)).collect(Collectors.toList());
            List<FriendsLifeCyclePhaseParam> needUpdateFriendsLifeCyclePhaseParamList = lifeCyclePhaseParamList.stream().filter(d->(d.getId() != null)).collect(Collectors.toList());
            List<FriendsLifeCyclePhaseDO> oldFriendsLifeCyclePhaseDOList = friendsLifeCyclePhaseMapper.selectList(new LambdaQueryWrapper<FriendsLifeCyclePhaseDO>().eq(FriendsLifeCyclePhaseDO::getCycleId, cycleId));

            if(Collections3.isNotEmpty(needUpdateFriendsLifeCyclePhaseParamList) && Collections3.isNotEmpty(oldFriendsLifeCyclePhaseDOList)){
                List<Long> needUpdatePhaseIdList = needUpdateFriendsLifeCyclePhaseParamList.stream().map(FriendsLifeCyclePhaseParam::getId).collect(Collectors.toList());
                List<Long> oldFullPhaseIdList  = oldFriendsLifeCyclePhaseDOList.stream().map(FriendsLifeCyclePhaseDO::getId).collect(Collectors.toList());
                HashSet<Long> needUpdatePhaseIdSet = new HashSet<>(needUpdatePhaseIdList);
                HashSet<Long> oldFullPhaseIdSet = new HashSet<>(oldFullPhaseIdList);
                oldFullPhaseIdSet.removeAll(needUpdatePhaseIdSet);
                List<Long> needDeletePhaseIdList = new ArrayList<>(oldFullPhaseIdSet);
                if(Collections3.isNotEmpty(needDeletePhaseIdList)) {
                    friendsLifeCyclePhaseMapper.delete(new LambdaQueryWrapper<FriendsLifeCyclePhaseDO>().in(FriendsLifeCyclePhaseDO::getId, needDeletePhaseIdList));
                }
            }
            if(Collections3.isNotEmpty(needInsertFriendsLifeCyclePhaseParamList)) {
                List<FriendsLifeCyclePhaseDO> needInsertFriendsLifeCyclePhaseDOList = needInsertFriendsLifeCyclePhaseParamList.stream().map(d->{
                    FriendsLifeCyclePhaseDO friendsLifeCyclePhaseDO = BeanUtil.convertBean(d, FriendsLifeCyclePhaseDO.class);
                    friendsLifeCyclePhaseDO.setCycleId(cycleId);
                    return friendsLifeCyclePhaseDO;
                }).collect(Collectors.toList());
                friendsLifeCyclePhaseMapper.insertBatchSomeColumn(needInsertFriendsLifeCyclePhaseDOList);
            }
            if(Collections3.isNotEmpty(needUpdateFriendsLifeCyclePhaseParamList)) {
                List<FriendsLifeCyclePhaseDO> needUpdateFriendsLifeCyclePhaseDOList = JsonUtils.jsonToList(needUpdateFriendsLifeCyclePhaseParamList,FriendsLifeCyclePhaseDO.class);
                friendsLifeCyclePhaseServiceImpl.updateBatch(needUpdateFriendsLifeCyclePhaseDOList);
            }
        }
        if(Collections3.isNotEmpty(lifeCycleRightParamList)){
            List<FriendsLifeCycleRightDO> oldFullFriendsLifeCycleRightDOList = friendsLifeCycleRightMapper.selectList(new LambdaQueryWrapper<FriendsLifeCycleRightDO>().eq(FriendsLifeCycleRightDO::getCycleId, cycleId));
            if(Collections3.isNotEmpty(oldFullFriendsLifeCycleRightDOList)) {
                List<FriendsLifeCycleRightDO> oldFullFriendsLifeCycleDepartRightDOList = oldFullFriendsLifeCycleRightDOList.stream().filter(d->(d.getEmployeeId() == null)).collect(Collectors.toList());
                List<FriendsLifeCycleRightParam> newFriendsLifeCycleDepartRightParamList = lifeCycleRightParamList.stream().filter(d->(d.getEmployeeId() == null)).collect(Collectors.toList());
                if(Collections3.isNotEmpty(oldFullFriendsLifeCycleDepartRightDOList) && Collections3.isNotEmpty(newFriendsLifeCycleDepartRightParamList)){
                   List<Long> oldFullDepartRightIdList = oldFullFriendsLifeCycleDepartRightDOList.stream().map(FriendsLifeCycleRightDO::getDepartmentId).collect(Collectors.toList());
                   List<Long> newDepartRightIdList =newFriendsLifeCycleDepartRightParamList.stream().map(FriendsLifeCycleRightParam::getDepartmentId).collect(Collectors.toList());
                   HashSet<Long> needDelOldFullDepartRightIdSet = new HashSet<>(oldFullDepartRightIdList);
                   HashSet<Long> needDelNewDepartRightIdSet = new HashSet<>(newDepartRightIdList);
                   needDelOldFullDepartRightIdSet.removeAll(needDelNewDepartRightIdSet);
                   List<Long> needDeleteOldDepartIdList = new ArrayList<>(needDelOldFullDepartRightIdSet);
                   if(Collections3.isNotEmpty(needDeleteOldDepartIdList)) {
                       friendsLifeCycleRightMapper.delete(new LambdaQueryWrapper<FriendsLifeCycleRightDO>()
                               .eq(FriendsLifeCycleRightDO::getCycleId, cycleId)
                               .eq(FriendsLifeCycleRightDO::getEmployeeId, null)
                               .in(FriendsLifeCycleRightDO::getDepartmentId, needDeleteOldDepartIdList));
                   }
                   HashSet<Long> needInsertOldFullDepartRightIdSet = new HashSet<>(oldFullDepartRightIdList);
                   HashSet<Long> needInsertNewDepartRightIdSet = new HashSet<>(newDepartRightIdList);
                   needInsertNewDepartRightIdSet.removeAll(needInsertOldFullDepartRightIdSet);
                   List<Long> needInsertDepartIdList = new ArrayList<>(needInsertNewDepartRightIdSet);
                   if(Collections3.isNotEmpty(needInsertDepartIdList)){
                       List<FriendsLifeCycleRightDO> needInsertDOS = new ArrayList<>();
                       needInsertDepartIdList.stream().forEach(d->{
                           FriendsLifeCycleRightDO friendsLifeCycleRightDO = new FriendsLifeCycleRightDO();
                           friendsLifeCycleRightDO.setId(IdGenerator.getId());
                           friendsLifeCycleRightDO.setCycleId(cycleId);
                           friendsLifeCycleRightDO.setDepartmentId(d);
                           friendsLifeCycleRightDO.setEmployeeId(null);
                           friendsLifeCycleRightDO.setCreateBy(UserUtils.getUserId());
                           friendsLifeCycleRightDO.setModifyBy(UserUtils.getUserId());
                           friendsLifeCycleRightDO.setModifyTime(LocalDateTime.now());
                           needInsertDOS.add(friendsLifeCycleRightDO);
                       });
                       friendsLifeCycleRightMapper.insertBatchSomeColumn(needInsertDOS);
                   }
                }
                List<FriendsLifeCycleRightDO> oldFullFriendsLifeCycleEmployeeRightDOList = oldFullFriendsLifeCycleRightDOList.stream().filter(d->(d.getEmployeeId() != null)).collect(Collectors.toList());
                List<FriendsLifeCycleRightParam> newFriendsLifeCycleEmployeeRightParamList = lifeCycleRightParamList.stream().filter(d->(d.getEmployeeId() != null)).collect(Collectors.toList());
                if(Collections3.isNotEmpty(newFriendsLifeCycleEmployeeRightParamList)){
                    if(Collections3.isEmpty(oldFullFriendsLifeCycleEmployeeRightDOList)){
                        List<FriendsLifeCycleRightDO> friendsLifeCycleRightDOList = newFriendsLifeCycleEmployeeRightParamList.stream().map(d->{
                            FriendsLifeCycleRightDO friendsLifeCycleRightDO = BeanUtil.convertBean(d, FriendsLifeCycleRightDO.class);
                            friendsLifeCycleRightDO.setId(IdGenerator.getId());
                            friendsLifeCycleRightDO.setCycleId(cycleId);
                            return friendsLifeCycleRightDO;
                        }).collect(Collectors.toList());
                        friendsLifeCycleRightMapper.insertBatchSomeColumn(friendsLifeCycleRightDOList);
                    }else{
                        List<Long> oldFullEmployeeRightIdList = oldFullFriendsLifeCycleEmployeeRightDOList.stream().map(FriendsLifeCycleRightDO::getEmployeeId).collect(Collectors.toList());
                        List<Long> newEmployeeRightIdList =newFriendsLifeCycleEmployeeRightParamList.stream().map(FriendsLifeCycleRightParam::getEmployeeId).collect(Collectors.toList());
                        HashSet<Long> needDelOldFullEmployeeRightIdSet = new HashSet<>(oldFullEmployeeRightIdList);
                        HashSet<Long> needDelNewEmployeeRightIdSet = new HashSet<>(newEmployeeRightIdList);
                        needDelOldFullEmployeeRightIdSet.removeAll(needDelNewEmployeeRightIdSet);
                        List<Long> needDeleteOldEmployeeIdList = new ArrayList<>(needDelOldFullEmployeeRightIdSet);
                        if(Collections3.isNotEmpty(needDeleteOldEmployeeIdList)) {
                            friendsLifeCycleRightMapper.delete(new LambdaQueryWrapper<FriendsLifeCycleRightDO>()
                                    .eq(FriendsLifeCycleRightDO::getCycleId, cycleId)
                                    .in(FriendsLifeCycleRightDO::getEmployeeId, needDeleteOldEmployeeIdList));
                        }
                        HashSet<Long> needInsertOldFullEmployeeRightIdSet = new HashSet<>(oldFullEmployeeRightIdList);
                        HashSet<Long> needInsertNewEmployeeRightIdSet = new HashSet<>(newEmployeeRightIdList);
                        needInsertNewEmployeeRightIdSet.removeAll(needInsertOldFullEmployeeRightIdSet);
                        List<Long> needInsertEmployeeIdList = new ArrayList<>(needInsertNewEmployeeRightIdSet);
                        if(Collections3.isNotEmpty(needInsertEmployeeIdList)){
                            Map<Long, Long> employeeDepartIdMap = newFriendsLifeCycleEmployeeRightParamList.stream().collect(Collectors.toMap(FriendsLifeCycleRightParam::getEmployeeId, FriendsLifeCycleRightParam::getDepartmentId, (o, n) -> n));
                            List<FriendsLifeCycleRightDO> needInsertDOS = new ArrayList<>();
                            needInsertEmployeeIdList.stream().forEach(d->{
                                FriendsLifeCycleRightDO friendsLifeCycleRightDO = new FriendsLifeCycleRightDO();
                                friendsLifeCycleRightDO.setId(IdGenerator.getId());
                                friendsLifeCycleRightDO.setCycleId(cycleId);
                                friendsLifeCycleRightDO.setDepartmentId(employeeDepartIdMap!=null?employeeDepartIdMap.get(d):null);
                                friendsLifeCycleRightDO.setEmployeeId(d);
                                friendsLifeCycleRightDO.setCreateBy(UserUtils.getUserId());
                                friendsLifeCycleRightDO.setModifyBy(UserUtils.getUserId());
                                friendsLifeCycleRightDO.setModifyTime(LocalDateTime.now());
                                needInsertDOS.add(friendsLifeCycleRightDO);
                            });
                            friendsLifeCycleRightMapper.insertBatchSomeColumn(needInsertDOS);
                        }
                    }
                }else{
                    if(Collections3.isNotEmpty(oldFullFriendsLifeCycleEmployeeRightDOList)){
                        List<Long> oldRightIds = oldFullFriendsLifeCycleEmployeeRightDOList.stream().map(FriendsLifeCycleRightDO::getId).collect(Collectors.toList());
                        friendsLifeCycleRightMapper.deleteBatchIds(oldRightIds);
                    }
                }
            }else{
                List<FriendsLifeCycleRightDO> friendsLifeCycleRightDOList = lifeCycleRightParamList.stream().map(d->{
                    FriendsLifeCycleRightDO friendsLifeCycleRightDO = BeanUtil.convertBean(d, FriendsLifeCycleRightDO.class);
                    friendsLifeCycleRightDO.setId(IdGenerator.getId());
                    friendsLifeCycleRightDO.setCycleId(cycleId);
                    return friendsLifeCycleRightDO;
                }).collect(Collectors.toList());
                friendsLifeCycleRightMapper.insertBatchSomeColumn(friendsLifeCycleRightDOList);
            }
        }
        return friendsLifeCycleMapper.updateById(entityDO) > 0;
    }

    @Override
    public FriendsLifeCycleVO view(Long id) {
        FriendsLifeCycleDO entityDO = friendsLifeCycleMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        Long cycleId = entityDO.getId();
        FriendsLifeCycleVO entityVO = BeanUtil.convertBean(entityDO, FriendsLifeCycleVO.class);
        if(entityVO != null) {
            List<CopDepartmentDO> copDepartmentDOS = copDepartmentMapper.selectList(new LambdaQueryWrapper<CopDepartmentDO>());
            Map<Long, String> copDepartmentNameCnMaps = Collections3.isNotEmpty(copDepartmentDOS)?copDepartmentDOS.parallelStream().collect(Collectors.toMap(CopDepartmentDO::getId, CopDepartmentDO::getName, (o, n) -> o)):null;
            List<CopEmployeeDO> copEmployeeDOS = copEmployeeMapper.selectList(new LambdaQueryWrapper<>());
            Map<Long, String> copEmployeeNameMaps =copEmployeeDOS.stream().collect(Collectors.toMap(CopEmployeeDO::getId, CopEmployeeDO::getEmployeeName, (o, n) -> n));

            List<FriendsLifeCyclePhaseDO> friendsLifeCyclePhaseDOS = friendsLifeCyclePhaseMapper.selectList(new LambdaQueryWrapper<FriendsLifeCyclePhaseDO>().eq(FriendsLifeCyclePhaseDO::getCycleId, cycleId));
            List<FriendsLifeCycleRightDO> friendsLifeCycleRightDOS = friendsLifeCycleRightMapper.selectList(new LambdaQueryWrapper<FriendsLifeCycleRightDO>().eq(FriendsLifeCycleRightDO::getCycleId, cycleId));
            if(Collections3.isNotEmpty(friendsLifeCyclePhaseDOS)){
                List<FriendsLifeCyclePhaseVO> friendsLifeCyclePhaseVOList = JsonUtils.jsonToList(friendsLifeCyclePhaseDOS, FriendsLifeCyclePhaseVO.class);
                friendsLifeCyclePhaseVOList.stream().forEach(d->{
                    String needNotifyStr = "员工跟进提醒：客户未跟进时间超过" + d.getDaysMissing() + "天后，于" + d.getTimeNotify() + "提醒员工跟进";
                    d.setNeedNotifyStr(needNotifyStr);
                    String needCycleNotifyStr = "周期提醒：员工首次提醒未跟进，每" + d.getDaysCycleNotify() + "天，于" + d.getTimeNotifyCycle() + "再次提醒";
                    d.setNeedCycleNotifyStr(needCycleNotifyStr);
                });

                entityVO.setLifeCyclePhases(friendsLifeCyclePhaseVOList);
            }
            if(Collections3.isNotEmpty(friendsLifeCycleRightDOS)){
                List<FriendsLifeCycleRightVO> friendsLifeCycleRightVOList = friendsLifeCycleRightDOS.stream().map(d->{
                    FriendsLifeCycleRightVO friendsLifeCycleRightVO = BeanUtil.convertBean(d, FriendsLifeCycleRightVO.class);
                    if(d.getEmployeeId() !=null){
                        String employeeName = copEmployeeNameMaps!=null?copEmployeeNameMaps.get(d.getEmployeeId()):"";
                        friendsLifeCycleRightVO.setEmployeeName(employeeName);
                        friendsLifeCycleRightVO.setName(employeeName);
                    }else{
                        String departmentName = copDepartmentNameCnMaps!=null?copDepartmentNameCnMaps.get(d.getDepartmentId()):"";
                        friendsLifeCycleRightVO.setDepartmentName(departmentName);
                        friendsLifeCycleRightVO.setName(departmentName);
                    }
                    return friendsLifeCycleRightVO;
                }).collect(Collectors.toList());
                entityVO.setLifeCycleRights(friendsLifeCycleRightVOList);
            }
            entityVO.setStatusDesc(PublishStatusEnum.getName(entityDO.getStatus()));
        }
        LogUtils.info("=========FriendsLifeCycleVO:{}=============",JsonUtils.toJsonStr(entityVO));
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeStatus(Long id, Integer status) {
        FriendsLifeCycleDO entityDO = friendsLifeCycleMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        entityDO.setStatus(status);
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        return friendsLifeCycleMapper.updateById(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id) {
        FriendsLifeCycleDO entityDO = friendsLifeCycleMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        friendsLifeCyclePhaseMapper.delete(new LambdaQueryWrapper<FriendsLifeCyclePhaseDO>().eq(FriendsLifeCyclePhaseDO::getCycleId, id));
        friendsLifeCycleRightMapper.delete(new LambdaQueryWrapper<FriendsLifeCycleRightDO>().eq(FriendsLifeCycleRightDO::getCycleId, id));
        return friendsLifeCycleMapper.deleteById(id) > 0;
    }
    /**
     * 校验唯一性
     *
     * @param param
     */
    public void checkUnique(FriendsLifeCycleParam param) {
        if (param == null) {
            throw new BusinessException("当前记录不存在!");
        }
        //code name确保等级唯一性
        LambdaQueryWrapper<FriendsLifeCycleDO> queryWrapper = new LambdaQueryWrapper<FriendsLifeCycleDO>()
                .ne(param.getId() != null, FriendsLifeCycleDO::getId, param.getId())
                .eq(FriendsLifeCycleDO::getName, param.getName());
        List<FriendsLifeCycleDO> dos = friendsLifeCycleMapper.selectList(queryWrapper);
        if (Collections3.isNotEmpty(dos)) {
            throw new BusinessException("已经存在同名的记录!");
        }
    }

}
